<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, ref, unref, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTree, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { eachTree } from '@/utils/tree'
import { getRoleShowApi, getFieldEnumApi } from '@/api/role'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const treeRef = ref<typeof ElTree>()

const order_range_field_enum = ref<any[]>([])

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: t('role.rolename'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Select',
    value: 1,
    componentProps: {
      options: [
        {
          label: t('userDemo.disable'),
          value: 0
        },
        {
          label: t('userDemo.enable'),
          value: 1
        }
      ]
    }
  },
  {
    field: 'order_range',
    label: t('role.order_range'),
    component: 'Select',
    componentProps: {
      options: order_range_field_enum
    }
  },
  {
    field: 'remark',
    label: t('role.remark'),
    component: 'Input'
  },
  {
    field: 'menu',
    label: t('role.menu'),
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex w-full">
                <div class="flex-1">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    node-key="id"
                    highlight-current
                    check-strictly={false}
                    expand-on-click-node={false}
                    data={treeData.value}
                    onNode-click={nodeClick}
                  >
                    {{
                      default: (data) => {
                        return <span>{data.data.title}</span>
                      }
                    }}
                  </ElTree>
                </div>
                <div class="flex-1">
                  {unref(currentTreeData) && unref(currentTreeData)?.role ? (
                    <ElCheckboxGroup v-model={unref(currentTreeData).permission}>
                      {unref(currentTreeData)?.role.map((v: any) => {
                        return <ElCheckbox label={v.id}>{v.title}</ElCheckbox>
                      })}
                    </ElCheckboxGroup>
                  ) : null}
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])

const currentTreeData = ref()
const nodeClick = (treeData: any) => {
  currentTreeData.value = treeData
}

const rules = reactive({
  name: [required()],
  role: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref([])
const getMenuList = async () => {
  const res = props.currentRow
    ? await getRoleShowApi({ id: props.currentRow.id })
    : await getRoleShowApi()
  if (res) {
    treeData.value = res.data.menu
    if (!props.currentRow) return
    await nextTick()
    setValues(res.data)
    for (const item of res.data.auth_ids) {
      await nextTick(() => {
        unref(treeRef)?.setChecked(item, true, false)
      })
    }
  }
}

const getFieldEnumList = async () => {
  const res = await getFieldEnumApi({ field: 'all' })
  order_range_field_enum.value = res.data.order_range
}

const dealBtnData = () => {
  const checked: any[] = []
  eachTree(treeData.value, (v) => {
    if (v.permission) checked.push(...v.permission)
  })
  return checked
}
const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const checkedKeys = unref(treeRef)?.getCheckedKeys() || []
    formData.auth_ids = [...checkedKeys, ...dealBtnData()]
    return formData
  }
}

onMounted(() => {
  getMenuList()
  getFieldEnumList()
})

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
